package com.lb.shopguide.ui.fragment.boss;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.ToastUtils;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.WxPaySuccessEvent;
import com.lb.shopguide.entity.pay.AuthResult;
import com.lb.shopguide.entity.pay.PayResult;
import com.lb.shopguide.event.boss.ChargeInEvent;
import com.lb.shopguide.event.boss.RookieChargeInMoneyEvent;
import com.lb.shopguide.http.method.ApiMethodBoss;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.ui.activity.BossMainActivity;
import com.lb.shopguide.ui.dialog.DialogChooseChargeinType;
import com.lb.shopguide.ui.view.ClearTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import okhttp3.RequestBody;

/**
 * Created by kang on 2017/12/26.
 * 充值页面
 */

public class FragmentChargeInMoney extends BaseCommonFragment implements View.OnClickListener {

    ClearTitleBar ctb;
    RelativeLayout layoutChargeType;
    TextView tvChargeType;
    EditText etMoney;
    TextView tvChargeIn;
    ImageView ivChargeType;

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private IWXAPI api;
    private String orderNum;
    private int chargeInType;

    private DialogChooseChargeinType dialogChooseChargeinType;



    public static FragmentChargeInMoney newInstance() {
        return new FragmentChargeInMoney();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_boss_charge_in;
    }

    @Override
    public void initData() {
        //默认是支付宝充值
        EventBus.getDefault().register(this);
        chargeInType = AppConstant.CHARGEIN_TYPE_ALIPAY;
        api = WXAPIFactory.createWXAPI(mContext, AppConstant.WECHAT_APP_ID);
        api.registerApp(AppConstant.WECHAT_APP_ID);
    }

    @Override
    public void initView() {
        ctb = view.findViewById(R.id.ctb);
        layoutChargeType = view.findViewById(R.id.layout_charge_type);
        tvChargeIn = view.findViewById(R.id.tv_charge_in);
        tvChargeType = view.findViewById(R.id.tv_charge_type);
        etMoney = view.findViewById(R.id.et_charge_money);
        ivChargeType = view.findViewById(R.id.iv_charge_type);

        ctb.setTvTitle("充值");
        ctb.setLeftImageSrc(R.drawable.iv_back);
        ctb.setOnLeftImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pop();
            }
        });

        tvChargeType.setText("支付宝");

        initListener();
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {
        ((BossMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
        finishRefresh();
    }

    private void initListener() {
        tvChargeIn.setOnClickListener(this);
        layoutChargeType.setOnClickListener(this);
    }

    private void showChooseChargeTypeDialog() {
        dialogChooseChargeinType = DialogChooseChargeinType.getDialogChooseChargeinType();
        dialogChooseChargeinType.show(getFragmentManager(), getPageTag());
        dialogChooseChargeinType.setChooseTypeListener(new DialogChooseChargeinType.OnSetChooseTypeListener() {
            @Override
            public void onAliPayClick() {
                dialogChooseChargeinType.dismiss();
                chargeInType = AppConstant.CHARGEIN_TYPE_ALIPAY;
                tvChargeType.setText("支付宝");
                ivChargeType.setImageResource(R.drawable.iv_alipay_pay_charge);
            }

            @Override
            public void onWechatPayClick() {
                dialogChooseChargeinType.dismiss();
                chargeInType = AppConstant.CHARGEIN_TYPE_WECHAT_PAY;
                tvChargeType.setText("微信支付");
                ivChargeType.setImageResource(R.drawable.iv_wechat_pay_charge);
            }
        });
    }

    private void sendRequestChargeInMoney() {
        RequestBody body = getRequestBody();
        if (body == null) {
            return;
        }
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == (ResponseCode.RESPONSE_SUCCESS)) {
//                        EventBus.getDefault().post(new ChargeInEvent());
                    if (chargeInType == AppConstant.CHARGEIN_TYPE_ALIPAY) {
                        //支付宝支付
                        aliPay(response.getReturnContent().toString());
                    } else if (chargeInType == AppConstant.CHARGEIN_TYPE_WECHAT_PAY) {
                        //微信支付
                        wechatPay(JsonUtil.getJsonObjectFromMap(response.getReturnContent()));
                    }
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }

        };
        ApiMethodBoss.chargeInOutMoney(new SimpleLbObserver(listener, otherListener), body,this, FragmentEvent.DESTROY_VIEW);
    }

    private RequestBody getRequestBody() {
        String money = etMoney.getText().toString();
        HashMap hashMap = new HashMap();
        hashMap.put("moneyAmount", money);
        hashMap.put("payMode", chargeInType);
        return BizUtil.getBodyFromMap(hashMap);
    }


    private void sendRequestConfirmOrderCharge() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    EventBus.getDefault().post(new RookieChargeInMoneyEvent());
                    EventBus.getDefault().post(new ChargeInEvent());
                    pop();
                }
            }
        };
        ApiMethodBoss.confirmOrderCharge(new SimpleLbObserver(listener, otherListener), orderNum,this,FragmentEvent.DESTROY_VIEW);
    }


    private void aliPay(final String orderInfo) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(getActivity());
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void wechatPay(JSONObject jsonContent) {
        try {
//            JSONObject jsonContent = jsonOne.getJSONObject("returnContent");
            PayReq req = new PayReq();
            orderNum = jsonContent.getString("rechargeOrderNum");
            req.appId = jsonContent.getString("appid");
            req.partnerId = jsonContent.getString("partnerid");
            req.prepayId = jsonContent.getString("prepayid");
            req.nonceStr = jsonContent.getString("noncestr");
            req.timeStamp = jsonContent.getString("timestamp");
            req.packageValue = jsonContent.getString("package");
//            req.packageValue = "Sign=WXPay";
            req.sign = jsonContent.getString("sign");
            req.extData = "android data"; // optional
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            api.registerApp(AppConstant.WECHAT_APP_ID);
            api.sendReq(req);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void getOrderNum(String info) {
        try {
            JSONObject jsonObject = new JSONObject(info);
            JSONObject jsonOrder = jsonObject.getJSONObject("alipay_trade_app_pay_response");
            if (jsonOrder.has("out_trade_no")) {
                orderNum = jsonOrder.getString("out_trade_no");
            } else {

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Subscribe
    public void onWxPaySuccess(WxPaySuccessEvent event) {
        sendRequestConfirmOrderCharge();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        getOrderNum(resultInfo);
                        sendRequestConfirmOrderCharge();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(mContext, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(mContext,
                                "授权成功" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(mContext,
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    @Override
    public String getPageTag() {
        return FragmentChargeInMoney.class.getName();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_charge_in:
                String money = etMoney.getText().toString();
                if (TextUtils.isEmpty(money)) {
                    ToastUtils.showShort("请输入充值金额");
                    break;
                }
                float fMoney = Float.parseFloat(money);
                if (fMoney == 0f) {
                    ToastUtils.showShort("请输入正确的充值金额");
                    break;
                }
                sendRequestChargeInMoney();
                break;
            case R.id.layout_charge_type:
                showChooseChargeTypeDialog();
                break;
        }
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}
